package com.tanger.im.service.notice;

import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.BeanUtils;
import com.tanger.im.entity.ImUserGroupNotice;
import com.tanger.im.mapper.IMUserGroupNoticeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description TODO
 * @Author Hchenbin
 * @Date 2023-12-25 15:42
 * @Version 1.0
 */
@Slf4j
@Service
public class IMUserGroupNoticeServiceImpl implements IMUserGroupNoticeService {

    @Autowired
    private IMUserGroupNoticeRepository repository;

    @Override
    public List<ImUserGroupNotice> findAll(Long groupId) {
        return Optional.ofNullable(repository.findAll(Example.of(new ImUserGroupNotice(groupId))))
                .orElseGet(Collections::emptyList);
    }

    @Override
    public ImUserGroupNotice findOne(Long groupId) {
        return Optional.ofNullable(repository.findAll(Example.of(new ImUserGroupNotice(groupId))))
                .map(ns -> ns.stream()
                        .max((p1, p2) -> (int) (p1.getUpdateTime() - p2.getUpdateTime()))
                        .get())
                .orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult save(Long groupId, ImUserGroupNotice notice) {
        if (Objects.isNull(notice.getId())) {
            notice.setGroupId(groupId);
            notice.setCreateTime(System.currentTimeMillis());
            notice.setUpdateTime(System.currentTimeMillis());
            repository.save(notice);
            return ActionResult.buildResultSuccess(notice);
        }
        ImUserGroupNotice nnotice = repository.findById(notice.getId())
                .orElseThrow(() -> new RuntimeException("公告不存在！"));
        BeanUtils.copyProperties(nnotice,nnotice);
        repository.saveAndFlush(nnotice);
        return ActionResult.buildResultSuccess(nnotice);
    }
}
